import { Injectable } from '@nestjs/common';
import { CreateCarDto } from './dto/create-car.dto';
import { UpdateCarDto } from './dto/update-car.dto';
import { Car } from './entities/car.entity';
import { Repository, getConnection } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../user/entities/user.entity';

@Injectable()
export class CarService {
  constructor(
    @InjectRepository(Car)
    private readonly carRepository: Repository<Car>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}
  async create(createCarDto: CreateCarDto) {
    const user = await this.userRepository.findOne({
      where: { id: createCarDto.userId },
    });

    const car = this.carRepository.create(createCarDto);
    car.user = user;
    return this.carRepository.save(car);
  }

  // 分页查询
  async skipFind(
    currentPage: number,
    pageSize: number,
    city: string,
    keywords?: string,
  ): Promise<Array<Car> | any> {
    let list = null;
    if (keywords) {
      list = await this.carRepository
        .createQueryBuilder('car')
        .leftJoinAndSelect('car.user', 'user')
        .where('user.city = :city', { city: city })
        .andWhere('car.isDelete = :isDelete', { isDelete: false })
        .andWhere('car.license_plate LIKE :license_plate', {
          license_plate: `%${keywords}%`,
        })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    } else {
      list = await this.carRepository
        .createQueryBuilder('car')
        .leftJoinAndSelect('car.user', 'user')
        .where('user.city = :city', { city: city })
        .andWhere('car.isDelete = :isDelete', { isDelete: false })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    }
    return {
      list: list[0],
      total: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }

  async findAll(): Promise<Car[] | any> {
    return this.carRepository.find();
  }

  // 根据ID查询数据
  async findOne(id: number): Promise<Car | any> {
    return this.carRepository.findOne({
      relations: ['user', 'service', 'photos', 'order'],
      where: { id },
    });
  }

  update(updateCarDto: UpdateCarDto) {
    const car = this.carRepository.create(updateCarDto);
    return this.carRepository.save(car);
  }

  remove(ids: number[]) {
    ids.forEach(async (id) => {
      try {
        await this.carRepository
          .createQueryBuilder()
          .update(Car)
          .set({
            isDelete: true,
          })
          .where('id = :id', { id: id })
          .execute();
      } catch (e) {
        console.log('🚀 ~ This is a result of console.log ~ ✨: 删除失败', id);
      }
    });
    return;
  }
}
